using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MusicManager : MonoBehaviour
{
    public static MusicManager instance;
    public AudioSource audioSource;
    public AudioClip[] clips;

    private Coroutine switchCorotine;
    private void Awake()
    {
        if (instance != null)
            Destroy(this);
        instance = this;
    }

    private void Start()
    {
        foreach (var c in clips)
        {
            c.LoadAudioData();
        }
    }

    public void stopMusic()
    {
        StartCoroutine(stop());
    }

    private IEnumerator stop()
    {
        while (audioSource.volume >= 0.1f)
        {
            audioSource.volume = Mathf.Lerp(audioSource.volume, 0, 0.05f);
            yield return null;
        }
        audioSource.Stop();
    }

    public void switchClip(int index)
    {
        if (audioSource != null&&instance!=null)
        {
            if(switchCorotine != null)
                StopCoroutine(switchCorotine);
            switchCorotine = StartCoroutine(switchC(index));
        }
    }

    private IEnumerator switchC(int index) 
    {
        if (audioSource.isPlaying)
        {
            while (audioSource.volume >= 0.1f)
            {
                audioSource.volume = Mathf.Lerp(audioSource.volume, 0, 0.05f);
                yield return null;
            }
            audioSource.Stop();
        }
        audioSource.clip = clips[index];
        audioSource.volume = 1;
        audioSource.Play();
        yield return null;
    }
        
}
